<template>
  <div>
    <el-upload
      :action="uploadUrl"
      :data="null"
      :headers="headers"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview"
      :limit="maxCount"
      :on-exceed="handleExceed"
      :accept="accept"
      :list-type="listType"
      :multiple="multiple"
    >
      <slot>
        <i v-if="listType === 'picture-card'" class="el-icon-plus"></i>
        <el-button v-else size="small" type="primary">上传文件</el-button>
      </slot>
      <slot name="tip" />
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <template v-if="isImage(dialogImageUrl)">
        <img width="100%" :src="dialogImageUrl" alt="Preview" />
      </template>
      <template v-else>
        <p>无法预览文件</p>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { policy } from "@/api/oss";
import store from "@/store";
import { getToken } from "@/utils/auth";

export default {
  name: "FileUpload",
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    maxCount: {
      type: Number,
      default: 5,
    },
    accept: {
      type: String,
      default: "*", // 允许任何文件
    },
    listType: {
      type: String,
      default: "text",
      validator: (value) => {
        return ["text", "picture", "picture-card"].includes(value);
      },
    },
    multiple: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        ossaccessKeyId: "",
        dir: "",
        host: "",
      },
      dialogVisible: false,
      dialogImageUrl: null,
      uploadUrl: `${process.env.BASE_API}oss/upload`,
    };
  },
  computed: {
    fileList() {
      return this.value.map((url, index) => ({
        name: `File-${index + 1}`,
        url,
      }));
    },
    headers() {
      return store.getters.token
        ? {
            Authorization: getToken(), // 携带 token
          }
        : {};
    },
  },
  methods: {
    emitInput(fileList) {
      const urls = fileList.map((file) => file.url);
      this.$emit("input", urls);
    },
    handleRemove(file, fileList) {
      this.emitInput(fileList);
    },
    handlePreview(file) {
      this.dialogVisible = true;
      this.dialogImageUrl = file.url;
    },
    beforeUpload(file) {
      return true;
    },
    handleUploadSuccess(res, file) {
      let url = res.data;

      this.fileList.push({ name: file.name, url });
      this.emitInput(this.fileList);
    },
    handleExceed() {
      this.$message({
        message: `最多只能上传 ${this.maxCount} 个文件`,
        type: "warning",
      });
    },
    isImage(fileUrl) {
      if (!fileUrl) return false;
      const urlWithoutQuery = fileUrl.split("?")[0]; // 去除 URL 中的查询参数
      return /\.(jpeg|jpg|png|gif|bmp|svg|webp)$/i.test(urlWithoutQuery);
    },
  },
};
</script>

<style scoped></style>
